<template>
  <el-dialog
    :title="configData.title + configData.afterTitle"
    v-model="configData.open"
    width="800px"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
    @close="handleClose"
    class="edit-data-dialog"
  >
    <div class="dialog-container">
      <el-form
        :model="dataContainer.form"
        ref="FormElRef"
        :inline="true"
        :rules="dataContainer.rules"
        label-width="100px"
      >
        <el-row :gutter="0">
          <el-col :span="12" :xs="6">
            <el-form-item label="员工ID" prop="employeeId">
              <el-input
                v-model="dataContainer.form.employeeId"
                placeholder="请输入员工ID"
                :disabled="
                  configData.isShow || configData.afterTitle === '-编辑'
                "
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="6">
            <el-form-item label="真实姓名" prop="realName">
              <el-input
                v-model="dataContainer.form.realName"
                placeholder="请输入真实姓名"
                :disabled="configData.isShow"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="6">
            <el-form-item label="联系方式" prop="contact">
              <el-input
                v-model="dataContainer.form.contact"
                placeholder="请输入联系方式"
                :disabled="configData.isShow"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="6">
            <el-form-item label="角色" prop="role">
              <el-select
                style="width: 100%"
                v-model="dataContainer.form.role"
                placeholder="请选择角色"
                :disabled="configData.isShow"
                clearable
              >
                <el-option label="管理员" value="admin" />
                <el-option label="用户" value="user" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="6" v-if="configData.afterTitle === '-添加'">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="dataContainer.form.password"
                type="password"
                placeholder="请输入密码"
                :disabled="configData.isShow"
                show-password
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="6" v-else-if="configData.afterTitle === '-编辑' && !configData.isShow">
            <el-form-item label="重置密码" prop="password">
              <el-input
                v-model="dataContainer.form.password"
                type="password"
                placeholder="留空表示不修改密码"
                show-password
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="24" :xs="6">
            <el-form-item
              label="创建时间"
              prop="createdAt"
              v-if="dataContainer.form.createdAt && configData.isShow"
            >
              <el-input v-model="formattedCreatedAt" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          @click="
            () => {
              dataContainer.closeType = 'cancel';
              configData.open = false;
            }
          "
        >
          取消
        </el-button>
        <el-button
          v-if="!configData.isShow"
          type="primary"
          @click="handleSubmit"
        >
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
/**
 * 用户数据编辑对话框
 * 使用外部调用的方式向内部传递数据
 * 使用promise的形式向外部通知状态
 */
import {
  defineComponent,
  ref,
  getCurrentInstance,
  reactive,
  nextTick,
  computed,
} from "vue";
import { mergeObjProperty } from "@/common/OtherTools";
import { getDictItem, initDataByConfig } from "@/common/OtherTools";
import { verifiedData } from "@/common/VerifiedTools";
import { messageError, messageSuccess } from "@/action/MessagePrompt.js";
import usersApi from "@/http/users.js";

//配置信息，初始化时使用
const configMap = {
  open: {
    default: false,
  },
  title: {
    default: "用户信息",
  },
  afterTitle: {
    default: "",
  },
  isShow: {
    //是否只是展示
    default: false,
  },
};

export default defineComponent({
  name: "EditDataDialog",
  components: {},
  setup() {
    const configData = reactive({});
    const FormElRef = ref(null); //组件实例
    const dataContainer = reactive({
      loading: false,
      closeType: "close", //关闭时的类型，是由确认取消按钮关闭的还是其他地方关闭的 confirm cancel
      resolve: undefined, //返给外部promise的回调
      reject: undefined,
      form: {},
      rules: {
        employeeId: [
          { required: true, message: "请输入员工ID", trigger: "blur" },
        ],
        realName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        contact: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
        ],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
        password: [
          { 
            required: configData.afterTitle === "-添加", 
            message: "请输入密码", 
            trigger: "blur" 
          },
        ],
      },
    });

    // 格式化创建时间
    const formattedCreatedAt = computed(() => {
      if (!dataContainer.form.createdAt) return "";
      return new Date(dataContainer.form.createdAt).toLocaleString();
    });

    const otherDataContainer = {
      castParams: {}, //向外部传递的参数
    };

    initDataByConfig(configData, {}, configMap);

    /**
     * 对话框关闭时的回调
     * 根据行为类型来判断调用那个回调函数
     */
    function handleClose() {
      if (dataContainer.closeType == "confirm") {
        dataContainer.resolve(otherDataContainer.castParams);
      } else {
        dataContainer.reject(
          dataContainer.closeType,
          otherDataContainer.castParams
        );
      }
    }

    /**
     * 初始化数据（外部调用）
     * 返回一个promise，以提供直接的回调
     */
    function initData(show = true, data = {}, option = {}) {
      initDataByConfig(configData, option, configMap);
      dataContainer.closeType = "close";
      dataContainer.loading = false;
      dataContainer.form = {};
      otherDataContainer.castParams = {};
      configData.open = show;

      nextTick(() => {
        // 确保verification字段是对象
        if (data.verification === undefined || data.verification === null) {
          data.verification = {};
        }
        dataContainer.form = data;
      });

      return new Promise((r, j) => {
        dataContainer.resolve = r;
        dataContainer.reject = j;
      });
    }

    /** 提交数据 */
    function handleSubmit() {
      /** 使用组件自带方法验证数据 */
      if (!FormElRef.value) return;
      FormElRef.value.validate((valid, e) => {
        if (e) {
          /** 打印报错信息 */
          let msg = e[Object.keys(e)[0]][0].message;
          messageError(msg);
        }
        if (!valid) return;

        dataContainer.loading = true;

        // 准备提交数据
        const formData = { ...dataContainer.form };

        // 根据操作类型决定调用哪个API
        if (configData.afterTitle === "-添加") {
          // 创建用户
          usersApi
            .createUser(formData)
            .then((res) => {
              messageSuccess("用户创建成功");
              otherDataContainer.castParams = res.data || res;
              dataContainer.closeType = "confirm";
              configData.open = false;
            })
            .catch((err) => {
              console.error("创建用户失败", err);
              messageError(err.response?.data?.message || "创建用户失败");
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        } else {
          // 编辑用户 - 移除不需要提交的字段
          delete formData.createdAt;
          delete formData.updatedAt;
          
          // 如果密码为空，则不更新密码字段
          if (!formData.password) {
            delete formData.password;
          }

          // 确保使用正确的id字段
          const userId = formData.id;
          if (!userId) {
            messageError("无法获取用户ID");
            dataContainer.loading = false;
            return;
          }

          usersApi
            .updateUser(userId, formData)
            .then((res) => {
              messageSuccess("用户信息更新成功");
              otherDataContainer.castParams = res.data || res;
              dataContainer.closeType = "confirm";
              configData.open = false;
            })
            .catch((err) => {
              console.error("更新用户信息失败", err);
              messageError(err.response?.data?.message || "更新用户信息失败");
            })
            .finally(() => {
              dataContainer.loading = false;
            });
        }
      });
    }

    return {
      configData,
      initData,
      dataContainer,
      handleClose,
      handleSubmit,
      FormElRef,
      formattedCreatedAt,
    };
  },
});
</script>

<style lang="scss" scoped>
.edit-data-dialog {
  .dialog-container {
    padding: 15px 15px 0 15px;
    box-sizing: border-box;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      margin: 10px 0;
      padding-bottom: 8px;
      border-bottom: 1px solid #eee;
    }
  }
  .dialog-footer {
    button {
      padding: 8px 20px;
    }
    > *:not(:last-child) {
      margin-right: 10px;
    }
  }
}
</style>
